//获取应用实例
const app = getApp();
const api = require('../../../../../utils/api.js');
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		bookList: null,  // 单词本列表
		wordNums: 0, // 单词总数量
		pageIndex: 0, 
		pageSize: 15,
		isData: false, //false表示还有数据,true表示没有更多数据
		scrollHeight: null, //可用窗口高度



	},

	onLoad(options) {
		this.setData({
			scrollHeight: app.globalData.scrollHeight,
		})
		
	},
	onShow() {
		this.setData({
			bookList: null,
			pageIndex: 0,
			isData: false,
		})
		this.getWordList();
	},
	toDetail(e) {
		let _self = this;
		let index = e.currentTarget.dataset.index;
		let idx = e.currentTarget.dataset.idx;
		let bookList = JSON.parse(JSON.stringify(_self.data.bookList)); // 多维json数组拷贝
		let arr = []; 
		let clickword = bookList[index].WordList.splice(idx,1)[0];  // 点击的单词
		for( let i = 0; i < bookList.length; i++){
			for(let j = 0; j < bookList[i].WordList.length; j++){
				arr.push(bookList[i].WordList[j]);
			}
		}
		console.log('单词本数组',_self.data.bookList)
		arr.unshift(clickword);
		app.globalData.wordDetailList = arr;
		wx.navigateTo({
			url: '/pages/spokenPackage/pages/wordbook/detail/detail'
		})
	},

	// 获取单词本列表
	getWordList() {
		
		let _self = this;
		if(_self.data.isData){
			wx.hideLoading()
			return
		}
		wx.showLoading({
			title: '加载中'
		})
		let dataDic = {
			OpenId: app.globalData.openId,
			PageIndex: _self.data.pageIndex,
			PageSize: _self.data.pageSize
		}
		api.methodGetWordBookList({
            dataDic,
            success: (res) => {
				wx.hideLoading()
				if(res.data.data.BookList.length<=0){
					_self.setData({
						isData: true
					})
					return
				}
				_self.setData({
					wordNums: res.data.data.WordNums,
				})
				if(_self.data.bookList == null){
					_self.setData({
						bookList: res.data.data.BookList,
						pageIndex: _self.data.pageIndex + 1
					})
				}else{
					_self.dataHandle(res.data.data.BookList)
				}
                
            },
            fail: (res) => {
                console.log("添加单词失败", res);
            },
            complete: (res) => {
                console.log(res.data);
            },
        })
	},

	// 数据处理
	dataHandle(res) {
		let _self = this;
		let newbookList = res;
		let bookList = JSON.parse(JSON.stringify(_self.data.bookList));
		let finalDate = bookList[bookList.length - 1].Date;
		let firstlDate = newbookList[0].Date;

		// 判断是否为当天的单词未加载完
		if(finalDate == firstlDate){
			console.log('当天未加载完');
			for( let i = 0; i < newbookList[0].WordList.length; i++ ){
				bookList[bookList.length-1].WordList.push(newbookList[0].WordList[i])
			}
			newbookList.shift();
			_self.setData({
				bookList: bookList.concat(newbookList),
				pageIndex: _self.data.pageIndex + 1
			})
		}else{
			console.log('当天已加载完');
			_self.setData({
				bookList: bookList.concat(newbookList),
				pageIndex: _self.data.pageIndex + 1
			})
		}
	},
	
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() {
		console.log('滚到底部了')
		this.getWordList();
	}, 

	

})